package com.example.news.News;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.example.news.R;

import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;


import java.io.IOException;

public class NewsContent extends AppCompatActivity {
    private String mUrl;
    private Document doc;
    private String html;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_content);

        Intent intent = getIntent();
        mUrl = intent.getStringExtra("url");

        //createWebView(Html(mUrl));
        createWebView(mUrl);


    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head><style>img{max-width: 100%; width:auto; height: auto;}</style></head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    private  String Html(String url){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    doc = Jsoup.connect(url).get();
                    html = String.valueOf(doc);
                    Log.i("TAGGG", "run: "+html);
                    //createWebView(html);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return html;
    }



    private void createWebView(String url) {
        // 创建 WebView 实例并通过 id 绑定我们刚在布局中创建的 WebView 标签

        final WebView webView = (WebView) findViewById(R.id.wv_main_news);

        // 设置 WebView 允许执行 JavaScript 脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //webView.getSettings().setJavaScriptEnabled(false);

        // 确保跳转到另一个网页时仍然在当前 WebView 中显示
        // 而不是调用浏览器打开
        webView.setWebViewClient(new WebViewClient());

        //
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);

        // 加载指定网页
        //webView.loadUrl(url);
        webView.loadDataWithBaseURL(null,getHtmlData(mUrl),"text/html","UTF-8",null);

    }

}